import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:free_music_player/models/song_model.dart';
import 'package:free_music_player/providers/music_provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:free_music_player/widgets/playing_screen.dart';

class SearchScreen extends StatefulWidget {
  const SearchScreen({super.key});

  @override
  State<SearchScreen> createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  final TextEditingController _searchController = TextEditingController();
  List<SongModel> _searchResults = [];
  bool _isSearching = false;

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _search() async {
    if (_searchController.text.isEmpty) return;

    setState(() {
      _isSearching = true;
    });

    try {
      final results = await Provider.of<MusicProvider>(context, listen: false)
          .searchSongs(_searchController.text);
      setState(() {
        _searchResults = results;
        _isSearching = false;
      });
    } catch (e) {
      setState(() {
        _isSearching = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('搜索失败: $e')),
      );
    }
  }

  void _playSong(SongModel song) {
    Provider.of<MusicProvider>(context, listen: false)
        .setPlaylistAndPlay([song], 0);

    // 导航到播放界面
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const PlayingScreen(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                labelText: '搜索歌曲、歌手或专辑',
                suffixIcon: IconButton(
                  icon: const Icon(Icons.search),
                  onPressed: _search,
                ),
                border: const OutlineInputBorder(),
              ),
              onSubmitted: (_) => _search(),
            ),
          ),

          // 搜索结果
          Expanded(
            child: _isSearching
                ? const Center(child: CircularProgressIndicator())
                : _searchResults.isEmpty
                    ? const Center(child: Text('暂无搜索结果'))
                    : ListView.builder(
                        itemCount: _searchResults.length,
                        itemBuilder: (context, index) {
                          final song = _searchResults[index];
                          return ListTile(
                            leading: CachedNetworkImage(
                              imageUrl: song.album.picUrl,
                              width: 50,
                              height: 50,
                              fit: BoxFit.cover,
                              placeholder: (context, url) => const
                                  CircularProgressIndicator(),
                              errorWidget: (context, url, error) =>
                                  const Icon(Icons.music_note),
                            ),
                            title: Text(song.name),
                            subtitle: Text(song.artistsName),
                            trailing: Text(song.formattedDuration),
                            onTap: () => _playSong(song),
                          );
                        },
                      ),
          ),
        ],
      ),
    );
  }
}